﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using _5E.Utils.EasyUI;
using Newtonsoft.Json;

namespace _5E.Utils.WebHelper
{
    public class AjaxHelper
    {
        public static string WebSiteUrl
        {
            get
            {
                string requestUrl = HttpContext.Current.Request.Url.AbsoluteUri;
                return requestUrl.Substring(0, requestUrl.LastIndexOf("/") + 1);
            }
        }

        public static string ToCombobox<T>(IEnumerable<T> list) where T : IComboboxData
        {
            var datas = list.Select(d => new { key = d.ToKey(), value = d.ToValue() });
            return ToJSON(datas);
        }

        public static string ToDatagrid(object obj, Int32 total = 0)
        {
            var data = new
            {
                total = total,
                rows = obj ?? new string[] { }
            };
            return ToJSON(data);
        }

        public static string ToData(object obj = null)
        {
            return ToJSON(obj ?? new object(), AjaxResultType.Data);
        }

        public static string ToInfo(string msg)
        {
            return ToJSON(msg, AjaxResultType.Info);
        }

        public static string ToWarning(string msg)
        {
            return ToJSON(msg, AjaxResultType.Warning);
        }

        public static string ToError(Exception ex)
        {
            return ToJSON(ex.Message.Replace("\r\n", ""), AjaxResultType.Error);
        }

        internal static string ToJSON(object obj, AjaxResultType type)
        {
            var data = new
            {
                type = type.ToString().ToLower(),
                data = obj
            };
            return ToJSON(data);
        }

        public static string ToJSON(object data)
        {
            string json = JsonConvert.SerializeObject(data);
            return json;
        }
    }

    public enum AjaxResultType
    {
        //信息
        Info,
        //警告
        Warning,
        //错误
        Error,
        //数据
        Data,
        EasyUI_Combobox,
        EasyUI_Datagrid
    }
}
